
package com.just521.xinshoutong.http;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.just521.xinshoutong.database.SDCardAccessor;

public class ImageDownLoader {

     private  HashMap<String, SoftReference<Drawable>> imageCache =  new HashMap<String, SoftReference<Drawable>>();
     private  String    folder ="ImageCache";
     
     public ImageDownLoader() {
            
     }
     
 
  	/***********************************************************************************************************
  	 * 加载图片接口
  	 **********************************************************************************************************/  
     public Drawable loadImage(final  String  filename ,final String imageUrl, final ImageCallback imageCallback) {
             if (imageCache.containsKey(imageUrl)) {
                 SoftReference<Drawable> softReference = imageCache.get(imageUrl);
                 Drawable drawable = softReference.get();
                 if (drawable != null) {
                     return drawable;
                 }
             }
             final Handler handler = new Handler() {
                 public void handleMessage(Message message) {
                	 if(null != imageCallback)
                		 imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
                 }
             };
             new Thread() {
                 @Override
                 public void run() {
                	
                     Drawable drawable  = loadImageFromSd(filename);
                     Log.d("debug", "get img");
                     if( drawable  == null ){
                    	 Log.d("debug", "req img from server");
                    	 drawable = loadImageFromUrl(imageUrl, filename);
                    	 
                     }
                     imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                     Message message = handler.obtainMessage(0, drawable);
                     handler.sendMessage(message);
                 }
             }.start();
             return null;
         }
     
     
     //================================================================================================================
     //私有内部接口	
 	/**
 	 * 加载sdcard图片
 	 */     
     private Drawable loadImageFromSd(String filename)
     {
     	String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();
         File file = new File(SDCardAccessor.getImageCachePath()+"/" + filename);

         if(file.exists())
         {
        	 Drawable drawable= new BitmapDrawable(BitmapFactory.decodeFile(SDCardAccessor.getImageCachePath()+"/" + filename));  
        	 return drawable;
         }
         
         else
         	return null;
     } 
     
	/**
	 * 加载网络图片
	 */ 
     private  Drawable loadImageFromUrl(String url, String filename) {
    	
    		Drawable d = null;
			try {
				URL u = new URL(url);
				
				HttpURLConnection con;
				con = (HttpURLConnection) u.openConnection();	
				con.setDoInput(true);
				con.connect();
				InputStream inputStream;
				inputStream = con.getInputStream();
				Bitmap b=BitmapFactory.decodeStream(inputStream); 
				d = new BitmapDrawable(b);
				saveImageToSdCard(b ,filename );
				con.disconnect();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			return d;
        }
      

    
 	/**
 	 * 保存图片到sdcard
 	 */ 
    private void saveImageToSdCard(Bitmap bm, String filename) {
        if (bm == null) {
            return;
        }
        
        
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {   	
            String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath();         
            createDir(SDCardAccessor.getImageCachePath());
     
            File file = new File(SDCardAccessor.getImageCachePath()+"/" + filename);
            try {
                file.createNewFile();
                OutputStream outStream = new FileOutputStream(file);
               bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                outStream.flush();
                outStream.close();

            } catch (FileNotFoundException e) {
                Log.e("zhaodsh","FileNotFoundException");
            } catch (IOException e) {
                Log.e("zhaodsh","IOException");
            }        	
        }

    }
    
    public static void createDir(String path) {
    	  
    		File file = new File(path);
    	    if (!file.exists()) {
    	    	file.mkdir();
    	    }
   }
    

    public interface ImageCallback {
        public void imageLoaded(Drawable imageDrawable, String imageUrl);
        
    }
   
    
}